package com.lglbc;


import com.lglbc.chatroom.Chat;
import com.lglbc.chatroom.ChatServiceGrpc;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.stub.StreamObserver;

import java.util.Scanner;

public class ChatroomClient2 {

    public static void main(String[] args) {
        ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 9090)
                .usePlaintext()
                .build();

        ChatServiceGrpc.ChatServiceStub stub = ChatServiceGrpc.newStub(channel);

        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter your username: ");
        String username = scanner.nextLine();

        StreamObserver<Chat.ChatMessage> chatStreamObserver = new StreamObserver<Chat.ChatMessage>() {
            @Override
            public void onNext(Chat.ChatMessage chatMessage) {
                System.out.println(chatMessage.getUsername() + ": " + chatMessage.getMessage());
            }

            @Override
            public void onError(Throwable throwable) {
                System.out.println("Error: " + throwable.getMessage());
            }

            @Override
            public void onCompleted() {
                System.out.println("Chat stream completed.");
            }
        };

        StreamObserver<Chat.JoinRequest> joinStreamObserver = stub.joinRoom(chatStreamObserver);

        joinStreamObserver.onNext(Chat.JoinRequest.newBuilder().setUsername(username).build());

        while (true) {
            String message = scanner.nextLine();
            if ("exit".equalsIgnoreCase(message)) {
                joinStreamObserver.onCompleted();
                break;
            }

            Chat.ChatMessage chatMessage = Chat.ChatMessage.newBuilder()
                    .setUsername(username)
                    .setMessage(message)
                    .build();
            stub.sendMessage(chatMessage, new StreamObserver<Chat.Empty>() {
                @Override
                public void onNext(Chat.Empty value) {}

                @Override
                public void onError(Throwable t) {
                    System.out.println("Error sending message: " + t.getMessage());
                }

                @Override
                public void onCompleted() {}
            });
        }

        channel.shutdown();
    }
}
